﻿using System;
using System.Threading.Tasks;
using WeShare.WeiXin.Common;
using WeShare.WeiXin.Common.EnumKey;

namespace WeShare.WeiXin.Mp.JsSdk.Entity
{
    public class ApiTicket : BaseRes
    {
        public string ticket { get; set; }
        public int expires_in { get; set; }
        public static string GetValue(TicketType type = TicketType.jsapi, string appId = "", Action<string> errorAction = null)
        {
            var config = OpenApi.GetConfig(appId);
            if (config == null)
            {
                errorAction?.Invoke("未查找到相关的注册信息，请调用OpenApi.Register(params ApiConfig[]  config)方法进行注册");
                return "";
            }

            var key = $"jsticket_{type.ToString()}_{appId}";
            if (OpenApi.IsUseRedisCache)
            {
                //从缓存中获取accessToken
                var value = OpenApi.redis.Get(key);
                if (!string.IsNullOrEmpty(value))
                {
                    return value;
                }
                var at = GetTicket(type, config.AppId);
                if (at.errcode != 0 && errorAction != null)
                {
                    errorAction(at.errmsg);
                    return "";
                }
                OpenApi.redis.Set(key, at.ticket, at.expires_in / 2);
                return at.ticket;
            }
            else
            {
                var value = CacheService.Get<string>(key);// CacheHelper.GetValue(appId);
                if (!string.IsNullOrEmpty(value)) return value;
                var ticket = GetTicket(type,config.AppId);
                if (ticket.errcode != 0 && errorAction != null)
                {
                    errorAction(ticket.errmsg);
                    return "";
                }
                CacheService.Add(key, ticket.ticket, ticket.expires_in / 2);
                //CacheHelper.Add(appId, accesstoken.access_token, DateTime.Now.AddSeconds(accesstoken.expires_in / 2));
                value = ticket.ticket;
                return value;
            }
        }
        private static ApiTicket GetTicket(TicketType type,string tokenOrAppId)
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={OpenApi.GetToken(tokenOrAppId)}&type={type.ToString()}";
            return HttpUtil.GetResult<ApiTicket>(url);
        }
#if !NET40
        private static async Task<ApiTicket> GetTicketAsync(TicketType type, string tokenOrAppId)
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={OpenApi.GetToken(tokenOrAppId)}&type={type.ToString()}";
            return await HttpUtil.GetResultAsync<ApiTicket>(url);
        }

        public static async Task<string> GetValueAsync(TicketType type, string appId = "", Action<string> errorAction = null)
        {
            var config = OpenApi.GetConfig(appId);
            if (config == null)
            {
                errorAction?.Invoke("未查找到相关的注册信息，请调用OpenApi.Register(params ApiConfig[]  config)方法进行注册");
                return "";
            }
            var key = $"jsticket_{type.ToString()}_{appId}";
            if (OpenApi.IsUseRedisCache)
            {
                //从缓存中获取accessToken
                var value = await OpenApi.redis.GetAsync(key);
                if (!string.IsNullOrEmpty(value))
                {
                    return value;
                }
                var at = await GetTicketAsync(type,config.AppId);
                if (at.errcode != 0 && errorAction != null)
                {
                    errorAction(at.errmsg);
                    return "";
                }
                OpenApi.redis.SetAsync(key, at.ticket, at.expires_in / 2);
                return at.ticket;
            }
            else
            {
                var value = CacheService.Get<string>(key);
                if (!string.IsNullOrEmpty(value)) return value;
                var ticket = await GetTicketAsync(type,config.AppId);
                if (ticket.errcode != 0 && errorAction != null)
                {
                    errorAction(ticket.errmsg);
                    return "";
                }
                CacheService.Add(key, ticket.ticket, ticket.expires_in / 2);
                value = ticket.ticket;
                return value;
            }
        }
#endif
    }
}